using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using AdminSG3L.Applicaticn.ServicesInterface;
using AdminSG3L.Applicaticn.Dtos;
using AdminSG3L.Applicaticn.Commands;
using System.Text.Json;
using System.Security.Claims;

namespace AdminSG3L.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController(IAuthService authService, IFileUploadService fileUploadService) : ControllerBase
{
    private readonly IAuthService _authService = authService;
    private readonly IFileUploadService _fileUploadService = fileUploadService;

    [HttpPost("login")]
    public async Task<ApiResponse<TokenResponseDto>> Login([FromBody] LoginDto dto)
    {
        return await _authService.LoginAsync(dto);
    }

    [HttpPost("register")]
    [AllowAnonymous]
    public async Task<ApiResponse<TokenResponseDto>> Register([FromBody] RegisterDto dto)
    {
        return await _authService.RegisterAsync(dto);
    }

    [HttpPost("refresh")]
    public async Task<ApiResponse<TokenResponseDto>> Refresh([FromBody] RefreshTokenDto dto)
    {
        return await _authService.RefreshTokenAsync(dto);
    }

    [HttpPost("revoke")]
    public async Task<ApiResponse<bool>> Revoke([FromBody] RefreshTokenDto dto)
    {
        return await _authService.RevokeRefreshTokenAsync(dto.RefreshToken);
    }

    [HttpPost("verify-identity")]
    public async Task<ApiResponse<bool>> VerifyIdentity([FromBody] ForgotPasswordVerifyDto dto)
    {
        return await _authService.VerifyIdentityAsync(dto);
    }

    [HttpPost("forgot-password/verify")]
    public async Task<ApiResponse<bool>> ForgotPasswordVerify([FromBody] ForgotPasswordVerifyDto dto)
    {
        return await _authService.VerifyIdentityAsync(dto);
    }

    [HttpPost("forgot-password/verify-user")]
    public async Task<ApiResponse<bool>> ForgotPasswordVerifyUser([FromBody] ForgotPasswordVerifyUserDto dto)
    {
        return await _authService.VerifyUserAsync(dto);
    }

    [HttpPost("reset-password")]
    public async Task<ApiResponse<bool>> ResetPassword([FromBody] ResetPasswordDto dto)
    {
        return await _authService.ResetPasswordAsync(dto);
    }

    [HttpPost("forgot-password/reset")]
    public async Task<ApiResponse<bool>> ForgotPasswordReset([FromBody] ResetPasswordDto dto)
    {
        return await _authService.ResetPasswordAsync(dto);
    }

    [HttpPost("send-email-code")]
    [AllowAnonymous]
    public Task<ApiResponse<bool>> SendEmailCode([FromBody] SendEmailCodeDto dto)
    {
        // 简单的邮箱验证码发送模拟
        if (string.IsNullOrWhiteSpace(dto.Email))
        {
            return Task.FromResult(ApiResponse<bool>.Fail("邮箱不能为空"));
        }
        
        // 对于测试邮箱，直接返回成功
        if (dto.Email.StartsWith("test@"))
        {
            return Task.FromResult(ApiResponse<bool>.Success(true, "验证码已发送（测试邮箱验证码: 123456）"));
        }
        
        // 实际项目中这里应该调用邮件服务发送验证码
        return Task.FromResult(ApiResponse<bool>.Success(true, "验证码已发送到您的邮箱"));
    }

    [HttpPost("forgot-password/send-email-code")]
    [AllowAnonymous]
    public Task<ApiResponse<bool>> ForgotPasswordSendEmailCode([FromBody] SendEmailCodeDto dto)
    {
        // 简单的邮箱验证码发送模拟
        if (string.IsNullOrWhiteSpace(dto.Email))
        {
            return Task.FromResult(ApiResponse<bool>.Fail("邮箱不能为空"));
        }
        
        // 邮箱格式验证
        var emailError = AdminSG3L.Applicaticn.Utils.FormValidator.ValidateEmail(dto.Email);
        if (emailError != null)
        {
            return Task.FromResult(ApiResponse<bool>.Fail(emailError));
        }
        
        // 对于测试邮箱，直接返回成功
        if (dto.Email.StartsWith("test@"))
        {
            return Task.FromResult(ApiResponse<bool>.Success(true, "验证码已发送（测试邮箱验证码: 123456）"));
        }
        
        // 实际项目中这里应该调用邮件服务发送验证码
        return Task.FromResult(ApiResponse<bool>.Success(true, "验证码已发送到您的邮箱"));
    }

    [HttpPost("verify-email-code")]
    [AllowAnonymous]
    public Task<ApiResponse<bool>> VerifyEmailCode([FromBody] VerifyEmailCodeDto dto)
    {
        var emailCodeError = AdminSG3L.Applicaticn.Utils.FormValidator.ValidateEmailCode(dto.Code, dto.Email);
        if (emailCodeError != null)
        {
            return Task.FromResult(ApiResponse<bool>.Fail(emailCodeError));
        }
        
        return Task.FromResult(ApiResponse<bool>.Success(true, "验证码验证成功"));
    }

    [HttpGet("captcha")]
    [AllowAnonymous]
    public Task<ApiResponse<CaptchaDto>> GetCaptcha()
    {
        // 简单的图形验证码生成模拟
        var captchaId = Guid.NewGuid().ToString();
        var captchaCode = Random.Shared.Next(1000, 9999).ToString();
        
        // 实际项目中应该将验证码存储到缓存中，并生成图片
        return Task.FromResult(ApiResponse<CaptchaDto>.Success(new CaptchaDto(captchaId, captchaCode), "验证码生成成功"));
    }

    [HttpPost("verify-captcha")]
    [AllowAnonymous]
    public Task<ApiResponse<bool>> VerifyCaptcha([FromBody] VerifyCaptchaDto dto)
    {
        // 简单的验证码验证模拟
        // 实际项目中应该从缓存中获取正确的验证码进行比较
        return Task.FromResult(ApiResponse<bool>.Success(true, "验证码验证成功"));
    }

    [HttpGet("profile")]
    [Authorize]
    public async Task<ApiResponse<UserProfileDto>> GetProfile()
    {
        try
        {
            // 简化获取用户信息逻辑
            var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value ??
                             User.FindFirst("sub")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                // 如果无法从JWT获取用户ID，返回基础信息
                var username = User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value ??
                              User.FindFirst("unique_name")?.Value ?? "Unknown";
                
                var basicProfile = new UserProfileDto(
                    Guid.NewGuid(),
                    username,
                    null,
                    $"{username}@example.com",
                    "",
                    null
                );
                
                return ApiResponse<UserProfileDto>.Success(basicProfile, "获取用户信息成功（基础信息）");
            }

            // 尝试从数据库获取用户信息
            try
            {
                var user = await _authService.GetUserByIdAsync(userId);
                if (user != null)
                {
                    var profile = new UserProfileDto(
                        user.Id,
                        user.Username,
                        user.NickName,
                        user.Email,
                        user.Avatar,
                        user.Description
                    );
                    
                    return ApiResponse<UserProfileDto>.Success(profile, "获取用户信息成功");
                }
            }
            catch (Exception)
            {
                // 数据库查询失败，返回基础信息
                var username = User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value ??
                              User.FindFirst("unique_name")?.Value ?? "Unknown";
                
                var fallbackProfile = new UserProfileDto(
                    userId,
                    username,
                    null,
                    $"{username}@example.com",
                    "",
                    null
                );
                
                return ApiResponse<UserProfileDto>.Success(fallbackProfile, "获取用户信息成功（数据库查询失败，使用缓存信息）");
            }
            
            return ApiResponse<UserProfileDto>.Fail("用户不存在");
        }
        catch (Exception ex)
        {
            return ApiResponse<UserProfileDto>.Fail($"获取用户信息失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 更新用户资料
    /// </summary>
    [HttpPut("profile")]
    [Authorize]
    public async Task<ApiResponse<UserProfileDto>> UpdateProfile([FromBody] UpdateProfileDto dto)
    {
        try
        {
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (string.IsNullOrEmpty(userId))
                return ApiResponse<UserProfileDto>.Fail("用户身份验证失败");

            var result = await _authService.UpdateProfileAsync(userId, dto);
            return result;
        }
        catch (Exception ex)
        {
            return ApiResponse<UserProfileDto>.Fail($"更新用户资料失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 修改密码
    /// </summary>
    [HttpPut("change-password")]
    [Authorize]
    public async Task<ApiResponse<object>> ChangePassword([FromBody] ChangePasswordDto dto)
    {
        try
        {
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (string.IsNullOrEmpty(userId))
                return ApiResponse<object>.Fail("用户身份验证失败");

            var result = await _authService.ChangePasswordAsync(userId, dto);
            return result;
        }
        catch (Exception ex)
        {
            return ApiResponse<object>.Fail($"修改密码失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 上传头像
    /// </summary>
    [HttpPost("upload-avatar")]
    [Authorize]
    public async Task<ApiResponse<string>> UploadAvatar([FromForm] IFormFile file)
    {
        try
        {
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (string.IsNullOrEmpty(userId))
                return ApiResponse<string>.Fail("用户身份验证失败");

            var result = await _fileUploadService.UploadFileAsync(file, "avatars");
            
            if (result.IsSuccess && !string.IsNullOrEmpty(result.Data))
            {
                // 更新用户头像URL到数据库
                await _authService.UpdateAvatarAsync(userId, result.Data);
                return ApiResponse<string>.Success(result.Data, "头像上传成功");
            }
            
            return ApiResponse<string>.Fail(result.Message);
        }
        catch (Exception ex)
        {
            return ApiResponse<string>.Fail($"头像上传失败: {ex.Message}");
        }
    }
} 